package com.iceframework.core.support.redis;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.iceframework.core.support.cache.ICacheService;
import com.iceframework.core.utils.JsonUtils;

@Service("cacheService")
public class RedisService implements ICacheService{

	@Autowired
	private StringRedisTemplate redisTemplate;

	/**
	 * 一周
	 */
	public static final long WEEK_SECONDS = 7 * 24 * 60 * 60;
	/**
	 * 30分钟
	 */
	public static final long Thrity_Minutes = 30 * 60;

	/**
	 * 将 key，value 存放到redis数据库中，永久不过期
	 *
	 * @param key
	 * @param value
	 */
	public void set(String key, Object value) {
		redisTemplate.opsForValue().set(key, JsonUtils.convertObj2String(value));
	}

	/**
	 * 将 key，value 存放到redis数据库中，设置过期时间单位是秒
	 *
	 * @param key
	 * @param value
	 * @param expireTime
	 */
	public void set(String key, Object value, long expireTime) {
		redisTemplate.opsForValue().set(key, JsonUtils.convertObj2String(value), expireTime, TimeUnit.SECONDS);
	}

	/**
	 * 判断 key 是否在 redis 数据库中
	 *
	 * @param key
	 * @return
	 */
	public boolean exists(final String key) {
		return redisTemplate.hasKey(key);
	}

	/**
	 * 获取与 key 对应的对象
	 * 
	 * @param key
	 * @param clazz 目标对象类型
	 * @param       <T>
	 * @return
	 */
	public <T> T get(String key, Class<T> clazz) {
		String s = get(key);
		if (s == null) {
			return null;
		}
		return JsonUtils.convertString2Obj(s, clazz);
	}

	/**
	 * 获取 key 对应的字符串
	 * 
	 * @param key
	 * @return
	 */
	public String get(String key) {
		return redisTemplate.opsForValue().get(key);
	}

	/**
	 * 删除 key 对应的 value
	 * 
	 * @param key
	 */
	public void delete(String key) {
		redisTemplate.delete(key);
	}

	/**
	 * 检测redis是否生存
	 * @return
	 */
	public String ping() throws RedisConnectionFailureException{
		return (String) redisTemplate.execute(new RedisCallback<Object>() {
			public String doInRedis(RedisConnection connection) {
				return connection.ping();
			}
		});
	}

}
